package cate.game.friend.aid;

import cate.common.util.GameResult;
import cate.game.db.SaveConstants;
import cate.game.db.facade.KvLoader;
import cate.game.db.mongo.kv.KvMongo;
import cate.game.framework.ModuleMan;
import cate.game.role.Role;
import cate.game.role.bag.hero.Hero;
import cate.game.util.IntervalCounter;
import easy.java.dev.note.NoteField;

import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

public class FriendAidManager extends ModuleMan {
    @NoteField("数据")
    private FriendAidSPO status;

    @Override
    public void initDependent() throws Exception {
        status = new KvLoader<>(game, FriendAidSPO.class, KvMongo.KEY_FRIEND_AID).getWithMerge((olds) -> {
            FriendAidSPO _status = new FriendAidSPO();
            _status.initialize();
            for(FriendAidSPO old : olds) {
                _status.eat(old);
            }
            return _status;
        });
        status.initialize();
    }

    public GameResult<Void> provide(Role role, int funcId, Hero hero) {
        return status.provide(funcId, role, hero);
    }

    public List<ServerRoleAidHero> getAidHeros(int funcId, Set<String> friends) {
        return status.getAidHeros(funcId, friends);
    }

    public ServerRoleAidHero getProvideHero(String roleUid, int funcId) {
        return status.getProvideHero(roleUid, funcId);
    }

    public ServerRoleAidHero borrow(String roleUid, int funcId) {
        return status.borrow(roleUid, funcId);
    }

    @Override
    public void shutdown() {
        game.db.kv.save(status);
    }

    @Override
    public void onDaySpan() {
        status.onDaySpan();
    }

    private static final AtomicInteger IDX = new AtomicInteger(0);
    private final IntervalCounter saveTrigger = new IntervalCounter(SaveConstants.FRIEND_AID_SAVE_SECONDS, IDX.getAndIncrement());
    public void tick(){
        if(saveTrigger.trigger()){
            long start = System.currentTimeMillis();
            shutdownSafe();
            log.info("game friendaid定时保存完成, cost{} ms", System.currentTimeMillis() - start);
        }
    }
}
